<?php
require_once ('Controller/Mobile/Common.inc.php');
require_once ('View/Result.inc.php');
require_once ('Model/GuestBookModel.inc.php');

final class Controller extends common {
	private $Result;
	private $Loader;
	private $Callback = NULL;
	public function __construct () {
		parent::__construct();
		$trace = debug_backtrace();
		if (isset ($trace[1])) {
			$this->Loader = $trace[1]['object'];
		}
	}

	public function execude () {
		header ('Content-Type: text/xml');
		$this->Result = new Result ();
		$this->GuestBookModel = new GuestBookModel ($this->mysql);
		if (array_key_exists ('action', $_REQUEST)) {
			$this->getFunction ($_REQUEST['action']);
		} else {
			$this->defaultPage ();
		}
		print $this->Result->Create ($this->Callback);
	}

	public function getFunction ($action) {
		switch ($action) {
			case 'post';
				$this->post ();
				break;
			case 'getGuestBook';
			default:
				$this->defaultPage ();
				break;
		}
	}

	private $GuestBookCount = 0;
	private $GuestBookitem = [];
	private $pagesize = 20;
	private $page = 0;
	private $GuestBookModel;
	public function defaultPage () {
		$this->Result->setModulename (sprintf ('M%sF%s', $this->Loader->module, __FUNCTION__));
		$this->GuestBookCount = $this->GuestBookModel->GetGuestBookCount ();
		if (array_key_exists ('page', $_REQUEST)) {
			if (ctype_digit ($_REQUEST['page']) && ($_REQUEST['page'] * $this->pagesize) <= $this->GuestBookCount) {
				$this->page = $_REQUEST['page'];
			} else {
				$this->Result->setErrorCode (1);
				return;
			}
		}
		$this->GuestBookitem = $this->GuestBookModel->GetGuestBookItems ($this->page * $this->pagesize, $this->pagesize);
		$this->Result->setStatus (200);
		$this->Result->setErrorCode (0);
		$this->Callback = array ($this, 'getGuestBookCallBack');
	}

	public function getGuestBookCallBack ($dom, $result) {
		$result->setAttribute ('Itemnum', $this->GuestBookCount );
		foreach ($this->GuestBookitem as $data) {
			$item = $dom->createElement ('item');
			foreach ($data as $key => $value) {
				$item->setAttribute ($key, $value);
			}
			$result->appendChild ($item);
		}
	}

	public function Post () {
		$this->Result->setModulename (sprintf ('M%sF%s', $this->Loader->module, __FUNCTION__));
		if (array_key_exists ('text', $_REQUEST) && $_REQUEST['text'] != '') {
			$this->Result->setStatus (200);
			$this->Result->setErrorCode (0);
			$this->GuestBookModel->AddGuestBookItem ($_REQUEST['text']);
		} else {
			$this->Result->setErrorCode (1);
		}
	}
}
?>
